<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-input placeholder="请输入内容" v-model="queryIfon.query" clearable @clear="searchList" class="input-with-select">
        <el-button slot="append" icon="el-icon-search" @click="searchList"></el-button>
      </el-input>
      <el-button type="primary" @click="addList" style="margin-left: 30px; margin-bottom: 10px;">添加用户</el-button>
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" class="el-icon-edit" @click="modForm(scope.row.id)" />
            <el-button type="danger" size="mini" class="el-icon-delete" @click="delForm(scope.row.id)" />
            <el-button type="info" size="mini" class="el-icon-setting" @click="setRole(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination :page-sizes="[1,10,50,100]" :page-size="queryIfon.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" :current-page="queryIfon.pagenum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog title="添加新用户" :visible.sync="dialogFormVisible" @close="clearAddForm" width="50%">
      <el-form :model="addform" label-width="150px" ref="addFormRef" :rules="addFormRules">
        <el-form-item label="姓名" prop="username">
          <el-input autocomplete="off" v-model="addform.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input autocomplete="off" v-model="addform.password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input autocomplete="off" v-model="addform.email" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input autocomplete="off" v-model="addform.mobile" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserPro">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户信息 -->
    <el-dialog title="编辑用户信息" :visible.sync="editFormVisible" width="50%">
      <el-form :model="modform" :rules="modFormRef" ref="modFormRef" label-width="150px">
        <el-form-item label="用户名">
          <el-input autocomplete="off" v-model="modform.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input autocomplete="off" v-model="modform.email" />
        </el-form-item>
        <el-form-item label="电话号码" prop="mobile">
          <el-input autocomplete="off" v-model="modform.mobile" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="modUserPro">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户:
          <el-input autocomplete="off" v-model="userInfo.username" disabled />
        </p>
        <p>当前的角色:
          <el-input autocomplete="off" v-model="userInfo.role_name" disabled />
        </p>
        <p>分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      queryIfon: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userList: [],
      total: 0,
      dialogFormVisible: false,
      editFormVisible: false,
      addform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      modform: {
        username: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [{
          required: true,
          message: '请输入用户名称',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 10,
          message: '用户名在3~10个字符之间',
          trigger: 'blur'
        }
        ],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 6,
          max: 15,
          message: '用户名在6~15个字符之间',
          trigger: 'blur'
        }
        ],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        },
        {
          validator: checkEmail,
          message: '邮箱格式不正确，请重新输入',
          trigger: 'blur'
        }
        ],
        mobile: [{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        },
        {
          validator: checkMobile,
          message: '手机号码不正确，请重新输入',
          trigger: 'blur'
        }
        ]
      },
      modFormRef: {
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        },
        {
          validator: checkEmail,
          message: '邮箱格式不正确，请重新输入',
          trigger: 'blur'
        }
        ],
        mobile: [{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        },
        {
          validator: checkMobile,
          message: '手机号码不正确，请重新输入',
          trigger: 'blur'
        }
        ]
      },
      setRoleDialogVisible: false,
      userInfo: {},
      rolesList: [],
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const {
        data: res
      } = await this.$http.get('http://kb.dekunlu.top/api/private/v1/users', {
        params: this.queryIfon
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (val) {
      this.queryIfon.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryIfon.pagenum = val
      this.getUserList()
    },
    async userStateChanged (row) {
      const {
        data: res
      } = await this.$http.put(
          `http://kb.dekunlu.top/api/private/v1/users/${row.id}/state/${row.mg_state}`
      )
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success('修改状态成功')
    },
    searchList () {
      this.getUserList()
    },
    addList () {
      this.dialogFormVisible = !this.dialogFormVisible
    },
    addUserPro () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整用户信息')
        const {
          data: res
        } = await this.$http.post('http://kb.dekunlu.top/api/private/v1/users', this.addform)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.getUserList()
      })
      this.dialogFormVisible = false
    },
    async modUserPro () {
      this.$refs.modFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整用户信息')
        const {
          data: res
        } = await this.$http.put(
          'users/' + this.modform.id,
          this.modform
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑用户失败')
        }
        this.$message.success('编辑用户成功')
        this.editFormVisible = !this.editFormVisible
        this.getUserList()
      })
      this.dialogFormVisible = false
    },
    clearAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    async modForm (id) {
      this.editFormVisible = !this.editFormVisible
      const {
        data: res
      } = await this.$http.get(`http://kb.dekunlu.top/api/private/v1/users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取信息失败')
      }
      this.modform = res.data
    },
    // 删除
    async delForm (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const {
        data: res
      } = await this.$http.delete('http://kb.dekunlu.top/api/private/v1/users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    async setRole (userInfo) {
      this.userInfo = userInfo
      const {
        data: res
      } = await this.$http.get('http://kb.dekunlu.top/api/private/v1/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }
      const {
        data: res
      } = await this.$http.put(
          `http://kb.dekunlu.top/api/private/v1/users/${this.userInfo.id}/role`, {
            rid: this.selectedRoleId
          }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
  .el-breadcrumb {
    margin-bottom: 10px;
  }

  .el-input {
    width: 460px;
  }

  .el-pagination {
    margin-top: 10px;
  }
</style>
